/*
 * @Author: your name
 * @Date: 2021-05-07 18:58:28
 * @LastEditTime: 2021-05-07 18:58:29
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \znfx-webe:\workplace\lab\Promise\index.js
 */

function Promise(excutor) {
  let self = this;
  self.status = 'pending';
  self.value = undefined;
  self.reason = undefined;


  self.onRejectedCallbacks = []//存放then失败的回调
  self.onResolvedCallbacks = []// 存放then成功的回调

  function resolve(value) {
    if (self.status === 'pending') {
      self.status = 'resolved';
      self.value = value;
      self.onResolvedCallbacks.forEach(fn => {
        fn();
      })
    }
  }
  function reject(reason) {
    if (self.status === 'pending') {
      self.status = 'rejected';
      self.reason = reason;
      self.onRejectedCallbacks.forEach(fn => {
        fn();
      })
    }
  }

  try {
    excutor(resolve, reject)
  } catch (error) {
    reject(error)
  }
}

Promise.prototype.then = function (onFullfilled, onRejected) {
  let self = this;
  if (self.status === 'resolved') {
    onFullfilled(self.value)
  }
  if (self.status === 'rejected') {
    onRejected(self.reason)
  }
  if (self.status === 'pending') {
    self.onResolvedCallbacks.push(function () {
      onFullfilled(self.value)
    });
    self.onRejectedCallbacks.push(function () {
      onRejected(self.reason)
    })
  }
}

module.exports = Promise